package com.skytech.component.monitor.enterprise_data_monitoring;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.WaterPollutionData;
import com.skytech.component.monitor.data.WaterPollutionDataDAO;
import com.skytech.component.monitor.util.FormateConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;


@Service
public class WaterPollutionService implements CrawlerScript{
    private static final Logger log = LoggerFactory.getLogger(WaterPollutionService.class);

    @Autowired
    private WaterPollutionDataDAO waterPollutionDataDAO;
    @Override
    public void start() {
        String url = "http://123.127.175.45:8082/ajax/GwtWaterHandler.ashx";
        try{
            Document document =  FormateConnection.createConnection(Jsoup.connect(url))
                    .data("Method","SelectRealData")
                    .post();
            JSONArray jsonArray= JSONArray.parseArray(document.body().text());
            for (Object o:jsonArray) {
                JSONObject json = JSONObject.parseObject(o.toString());
                WaterPollutionData waterPollutionData=new WaterPollutionData();

                waterPollutionData.setDateTime(json.getString("dateTime"));
                waterPollutionData.setSiteName(json.getString("siteName"));

                List<WaterPollutionData> History = waterPollutionDataDAO.findAll(Example.of(waterPollutionData));

                if(History.isEmpty()){
                    waterPollutionData.setId(UUID.randomUUID().toString());
                    waterPollutionData.setPh(json.getString("pH"));
                    waterPollutionData.setDissolvedOxygen(json.getString("DO"));
                    waterPollutionData.setNh4(json.getString("NH4"));
                    waterPollutionData.setCodmn(json.getString("CODMn"));
                    waterPollutionData.setToc(json.getString("TOC"));
                    waterPollutionData.setLevel(json.getString("level"));
                    waterPollutionData.setAttribute(json.getString("attribute"));
                    waterPollutionData.setStatus(json.getString("status"));
                    waterPollutionData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    waterPollutionDataDAO.save(waterPollutionData);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }finally {
            log.info("数据爬取结束");
        }


    }
}
